from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import logging

# 初始化Flask应用
app = Flask(__name__)

# 配置数据库连接
# 格式：mysql+pymysql://用户名:密码@主机地址:端口/数据库名
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:hui123456@localhost:3306/sms'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭追踪修改，提高性能

# 初始化数据库
db = SQLAlchemy(app)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 定义短信模型
class ReceivedSMS(db.Model):
    __tablename__ = 'received_sms'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    sender = db.Column(db.String(20), nullable=False)
    content = db.Column(db.Text, nullable=False)
    receive_time = db.Column(db.DateTime)
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<SMS from {self.sender} at {self.receive_time}>'

# 创建数据表（如果不存在）
with app.app_context():
    db.create_all()

# 定义接收短信的接口
@app.route('/webhook/sms', methods=['POST'])
def receive_sms():
    try:
        # 获取请求数据
        data = request.json
        
        # 验证必要的字段
        if not all(k in data for k in ('sender', 'content')):
            logger.warning('缺少必要的字段')
            return jsonify({'status': 'error', 'message': '缺少必要的字段（sender或content）'}), 400
        
        # 提取数据
        sender = data['sender']
        content = data['content']
        # 尝试获取接收时间，如果没有则使用当前时间
        receive_time_str = data.get('receive_time')
        receive_time = datetime.fromisoformat(receive_time_str) if receive_time_str else datetime.now()
        
        # 创建新的短信记录
        new_sms = ReceivedSMS(
            sender=sender,
            content=content,
            receive_time=receive_time
        )
        
        # 保存到数据库
        db.session.add(new_sms)
        db.session.commit()
        
        logger.info(f'成功接收并保存短信，发送者: {sender}')
        return jsonify({'status': 'success', 'message': '短信已成功保存', 'id': new_sms.id}), 201
        
    except Exception as e:
        # 发生错误时回滚事务
        db.session.rollback()
        logger.error(f'处理短信时发生错误: {str(e)}')
        return jsonify({'status': 'error', 'message': f'处理失败: {str(e)}'}), 500

# 健康检查接口，用于验证服务是否正常运行
@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'healthy', 'message': '服务运行正常'}), 200

# 启动应用
if __name__ == '__main__':
    # 注意：debug=True仅用于开发环境，生产环境需要设置为False
    # host='0.0.0.0'表示允许所有网络接口访问
    app.run(host='0.0.0.0', port=5000, debug=True)
